package com.bangdream.michelia.presenter.base;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.bangdream.michelia.application.AppCurrentUser;
import com.bangdream.michelia.application.MainApplication;
import com.bangdream.michelia.entity.BaseEntity;
import com.bangdream.michelia.entity.ErrorMessageBean;
import com.bangdream.michelia.entity.UserInfoBean;
import com.bangdream.michelia.tool.rejava.BaseObserverEntityNormalHttp;
import com.bangdream.michelia.tool.retrofithttp.RetroFactory;
import com.bangdream.michelia.tool.retrofithttp.TokenLoader;
import com.bangdream.michelia.utils.SPUtils;
import com.bangdream.michelia.utils.ToastUtil;
import com.bangdream.michelia.view.activity.currency.LoginActivity;

import org.reactivestreams.Publisher;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.Callable;

import io.reactivex.Flowable;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.Single;
import io.reactivex.SingleEmitter;
import io.reactivex.SingleOnSubscribe;
import io.reactivex.SingleSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * Created by Mr.Wang on 2018/3/19.
 * 909732184@qq.com
 * https://www.jianshu.com/p/2fd2d5dac94e
 * https://blog.csdn.net/qq122627018/article/details/51684882
 */

public abstract class BasePresenter<V> {
    private static final String TAG = "okhttp";
    private WeakReference<V> weakRefView;
    private static final String ERROR_TOKEN = "error_token";
    private static final String ERROR_RETRY = "error_retry";
    //Function是对Observable的一些基础设置
    public ObservableTransformer<Observable, ObservableSource> composeFunction;
    //重试的次数
    private final long RETRY_TIMES = 0;
    public Dialog pd;

    public Dialog getPd() {
        return pd;
    }

    public void setPd(Dialog pd) {
        this.pd = pd;
    }

    public void attach(V view) {
        weakRefView = new WeakReference<V>(view);
    }

    public void detach() {
        if (isAttach()) {
            weakRefView.clear();
            weakRefView = null;
        }
    }

    public V obtainView() {
        return isAttach() ? weakRefView.get() : null;
    }

    protected boolean isAttach() {
        return weakRefView != null &&
                weakRefView.get() != null;
    }

    public BasePresenter() {
        composeFunction = new ObservableTransformer<Observable, ObservableSource>() {
            @Override
            public ObservableSource apply(Observable observable) {
                return observable
                        //将被观察者放在子线程，将观察者放在主线程
                        .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                        //doOnSubscribe是在事件发送前进行的操作，所以我们可以做一些初始化的工作
                        .doOnSubscribe(new Consumer<Disposable>() {
                            @Override
                            public void accept(Disposable disposable) throws Exception {
                                if(pd != null && !pd.isShowing()){
                                    pd.show();
                                }
                            }
                        });
//
            }
        };


    }

    //将错误装换为文本
    @SuppressLint("CheckResult")
    public void TransformationErrorText(String errorMessageCode) {
        Observable observable = RetroFactory.getInstance().getDict("message",errorMessageCode);
        observable.compose(composeFunction)
                .subscribe(new BaseObserverEntityNormalHttp<ErrorMessageBean>(null,pd) {
                    @Override
                    public void onHandleSuccess(ErrorMessageBean bean) {
                        if(bean!=null){
                            ToastUtil.showShortToast(MainApplication.getContext(),bean.getLabel()+"");
                            if(bean.getLabel().contains("用户信息不存在")){
//                                AppCurrentUser.getInstance().EndSign();
//                                Intent intent = new Intent(MainApplication.getContext(), LoginActivity.class);
//                                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                                MainApplication.getContext().startActivity(intent);
                            }
                        }
                    }
                    @Override
                    public void onError(Throwable e){

                    }
                });
    }

    //获得请求成功后的描述
    protected String getDescribe(Object object) {
        return object == null ? "0" : "请求成功";
    }


    private Observable<BaseEntity> getUserObservable(final BaseEntity token) {

        Observable<BaseEntity> observable = Observable.create(new ObservableOnSubscribe<BaseEntity>() {

            @Override
            public void subscribe(ObservableEmitter<BaseEntity> emitter) throws Exception {
                Log.d(TAG, ":" + "收到信息2=" + token);

                if (token.getMessage() != null) {
                    if (token.getMessage().contains("ZUUL_ERROR_00002")) {
                        Log.d(TAG, "发送异常----" + token);

                        emitter.onError(new Throwable(ERROR_TOKEN));
                    } else {
                        emitter.onNext(token);
                    }
                } else {
                    emitter.onNext(token);
                }

            }
        });

        return observable;


    }

}
